<?php
/*
 * Created on Sep 13, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
 
include_once("./configure/configure.php");		//--> global var
include_once('./configure/ppsdk_include_path.inc');
include_once("customerSession.inc.php");
include_once("Smarty.class.php");				//--> out template
include_once("Common.php");
include_once("UploadFiles.php");				//--> UploadFiles
include_once("Session.php");					//-- Session
include_once("Strings.php");					//--> String utils

include_once ("orders/OrdersAccount.php");			//-- for payment
include_once ("CustomerDao.php");					//-- for payment
include_once ("AddressBookDao.php");				//-- for payment

include_once("orders/Cart.php");					//--> Cart
include_once("orders/CartProduct.php");				//--> Cart
include_once("orders/CartProductAttribute.php");	//--> Cart
include_once("orders/OrdersInfo.php");				//-- for payment

include_once("CouponImpl.php");						//--> coupon impl
include_once("CouponCustomer.php");
include_once("CouponDomain.php");					//--> coupon domain

include_once ("paypal-app/PaypalInfo.php");			//-- for payment
include_once ("paypal-app/PaymentPro.php");			//-- for payment

include_once("Zone.php");						//--> Zone
include_once("Country.php");					//--> Country
include_once ("Password.php");					//-- Password

require_once('includeHttps.php');

session_start();

$common 			= new Common();
$objCustomerDao 	= new CustomerDao();

$objOrdersInfo		= new OrdersInfo();

$objSession			= new Session(DB_TAG_SYSTEM, SESSION_TABLE_NAME);	//-- session
$objCart 			= new Cart();		//--> Cart
$objStrings 		= new Strings();
$objPassword 		= new Password();

$objZone			= new Zone(0);										//--> Zone
$objCountry			= new Country(0);									//--> Country

$objPaymentPro		= new PaymentPro();
$objPaypalInfo		= new PaypalInfo();

/*----- check session -----*/
$isLogin	= false;

if($objSession->exist()) {
	$isLogin	= true;
	
	$customerid = $objSession->getUserID();
	
	$customer = $common->getRow(DB_TAG_SYSTEM, "SELECT * FROM customers WHERE id =$customerid");
  		
	$objCustomerDao->setID($customerid);
	$objCustomerDao->setFirstName($customer['firstname']);
    $objCustomerDao->setLastName($customer['lastname']);
    $objCustomerDao->setEmail($customer['email']);
    $objCustomerDao->setTelephone($customer['telephone']);
    $objCustomerDao->setFax($customer['fax']);
    $objCustomerDao->setNewsletter($customer['newsletter']);
    $objCustomerDao->setPaypalEC($customer['paypal_ec']);
    $objCustomerDao->setPaypalPayerid($customer['paypal_payerid']);
    $objCustomerDao->setPassword($customer['password']);
    $objCustomerDao->setCreatedTime('UTC_TIMESTAMP()');
    $objCustomerDao->setModifiedTime('UTC_TIMESTAMP()');
    $objCustomerDao->setCountryid($customer['countryid']);
    $objCustomerDao->setAddressid($customer['default_address_id']);
    
    $_SESSION['customerInfo'] = serialize($objCustomerDao);
}

if($_SESSION['cart']){
	$objCart = unserialize($_SESSION['cart']);
}

if(isset($_SESSION['ordersInfo'])){
	$objOrdersInfo = unserialize($_SESSION['ordersInfo']);
}

if($_SESSION['paypalInfo']){
	$objPaypalInfo = unserialize($_SESSION['paypalInfo']);
}

$productTotal 	= $objCart->getAmount();
if($productTotal == 0){
	$location = HOME_URL . "/viewCart.php";
	
	header("Location: $location");
	exit;
}


$zoneid = 0;

$error_message 	= '';
$paymentMethod	= '';

if(isset($_POST['Submit'])){
	$comments		= $_POST['comments'];
	$paymentMethod 	= $_POST['paymentMethod'];
	
	$objCart->setStatus(Cart::STATUS_LOOKED);
	
	$objOrdersInfo->setPaymentMethod($paymentMethod);
	$objOrdersInfo->setComments($comments);
	
	$_SESSION['ordersInfo'] = serialize($objOrdersInfo);
	$_SESSION['cart'] 		= serialize($objCart);
	
	if($paymentMethod == OrdersInfo::DIRECT_PAYMENT){
		$cc_firstname		= $_POST['cc_firstname'];
		$cc_lastname		= $_POST['cc_lastname'];
		$cc_type			= $_POST['cc_type'];
		$cc_number			= $_POST['cc_number'];
		
		$cc_expires_year	= $_POST['cc_expires_year'];
		$cc_expires_month	= $_POST['cc_expires_month'];
		$cc_checkcode		= $_POST['cc_checkcode'];
		
		$objPaypalInfo->setCCFirstName($cc_firstname);
		$objPaypalInfo->setCCLastName($cc_lastname);
		$objPaypalInfo->setCCType($cc_type);
		$objPaypalInfo->setCCNumber($cc_number);
		$objPaypalInfo->setCCYear($cc_expires_year);
		$objPaypalInfo->setCCExpiresMonth($cc_expires_month);
		
		$objPaypalInfo->setCCCheckCode($cc_checkcode);
		
		$_SESSION['paypalInfo'] = serialize($objPaypalInfo);
		
		if($isLogin){
			$location = 'checkoutFinish.php';
		}else{
			$location = HOME_URL . "/viewCart.php";
		}
		
//		if(empty($customerid)){
//			$deliveryAddress = $objOrdersInfo->getDeliveryAddress();
//			
//			$objCustomerDao->setID(0);
//			$objCustomerDao->setFirstName($deliveryAddress->getFirstName());
//		    $objCustomerDao->setLastName($deliveryAddress->getLastName());
//		    $objCustomerDao->setEmail("");
//		    $objCustomerDao->setTelephone($deliveryAddress->getPhoneNumber());
//		    $objCustomerDao->setFax('');
//		    $objCustomerDao->setNewsletter(0);
//		    $objCustomerDao->setPaypalEC(1);
//		    $objCustomerDao->setPaypalPayerid(0);
//		    $objCustomerDao->setPassword('');
//		    $objCustomerDao->setCreatedTime('UTC_TIMESTAMP()');
//		    $objCustomerDao->setModifiedTime('UTC_TIMESTAMP()');
//		    $objCustomerDao->setCountryid($objOrdersInfo->getDeliveryAddress()->getCountryid());
//		    $objCustomerDao->setNewsletter('unsubscribed');
//			
//			$_SESSION['customerInfo'] = serialize($objCustomerDao);
//		}
		
		$location = 'checkoutFinish.php';
		
		header("Location: $location");
		exit;
	}else if($paymentMethod == OrdersInfo::MONEY_ORDER){
		if($isLogin){
			$location = 'checkoutFinish.php';
		}else{
			$location = HOME_URL . "/viewCart.php";
		}
		
//		if(empty($customerid)){
//			$deliveryAddress = $objOrdersInfo->getDeliveryAddress();
//			
//			$objCustomerDao->setID(0);
//			$objCustomerDao->setFirstName($deliveryAddress->getFirstName());
//		    $objCustomerDao->setLastName($deliveryAddress->getLastName());
//		    $objCustomerDao->setEmail("");
//		    $objCustomerDao->setTelephone($deliveryAddress->getPhoneNumber());
//		    $objCustomerDao->setFax('');
//		    $objCustomerDao->setNewsletter(0);
//		    $objCustomerDao->setPaypalEC(1);
//		    $objCustomerDao->setPaypalPayerid(0);
//		    $objCustomerDao->setPassword('');
//		    $objCustomerDao->setCreatedTime('UTC_TIMESTAMP()');
//		    $objCustomerDao->setModifiedTime('UTC_TIMESTAMP()');
//		    $objCustomerDao->setCountryid($objOrdersInfo->getDeliveryAddress()->getCountryid());
//		    $objCustomerDao->setNewsletter('unsubscribed');
//			
//			$_SESSION['customerInfo'] = serialize($objCustomerDao);
//		}
//		
//		$location = 'checkoutFinish.php';
		
		header("Location: $location");
		exit;
	}else if($paymentMethod == OrdersInfo::EXPRESS_CHECKOUT){
		$location = "expressCheckout.php";
		
		header("Location: $location");
		exit;
	}
}


if(isset($_POST['address_submit'])){
	$firstname 		= $_POST['firstname'];
	$lastname 		= $_POST['lastname'];
	$countryId		= $_POST['countryId'];
	$zipcode		= $_POST['zipcode'];
	
	
	$city			= $_POST['city'];
	$street			= $_POST['street'];
			
	$state			= $_POST['state'];
	$zoneid			= $_POST['zoneid'];
	
	$phoneNumber	= $_POST['phoneNumber'];
		
	if(empty($firstname))
		$error_message = 'First name is required.';
	else if(empty($lastname)){
		$error_message = 'Last name is required.';
	}else if(empty($street)){
		$error_message = 'Street address is required.';
	}else if(empty($zipcode)){
		$error_message = 'Zipcode is required.';
	}else if(empty($city)){
		$error_message = 'City is required.';
	}else if(empty($state) && empty($zoneid)){
		$error_message = 'State is required.';
	}else if(empty($phoneNumber)){
		$error_message = 'Phone number is required.';
	}
	
	if(empty($error_message)){
		if(!empty($zoneid)){
			$sql 	= "SELECT code FROM zones WHERE id = $zoneid";
			
			$state = $common->getColumn(DB_TAG_SYSTEM, $sql);
		}
		if(!empty($countryId)){
			$sql 	= "SELECT name FROM countries WHERE id = $countryId";
			
			$country = $common->getColumn(DB_TAG_SYSTEM, $sql);
		}
		
		$objAddressBookDao	= new AddressBookDao();
		$objAddressBookDao->setFirstName($firstname);
		$objAddressBookDao->setLastName($lastname);
		$objAddressBookDao->setCountryid($countryId);
		$objAddressBookDao->setStreet($street);
		$objAddressBookDao->setCity($city);
		$objAddressBookDao->setState($state);
		$objAddressBookDao->setZoneid($zoneid);
		$objAddressBookDao->setZipcode($zipcode);
		$objAddressBookDao->setPhoneNumber($phoneNumber);
		$objAddressBookDao->setCountry($country);
		
		$objOrdersInfo->setDeliveryAddress($objAddressBookDao);
		
		
		// rigester guest customer
		$guestEmail = $objOrdersInfo->getEmail();
		if(!empty($guestEmail) && !$isLogin){
			$customer = $common->getRow(DB_TAG_SYSTEM, "SELECT id FROM customers WHERE email ='$guestEmail'");
			
			if(count($customer) == 0){
				$salt = '46z3haZzegmn676PA3rUw2vrkhcLEn2p1c6gf7vp2ny4u3qqfqBh5j6kDhuLmyv9xf';
		        srand((double)microtime() * 1000000);
		        $password = '';
		        for ($x = 0; $x < 7; $x++) {
		            $num = rand() % 33;
		            $tmp = substr($salt, $num, 1);
		            $password = $password . $tmp;
		        }
		        
		        $objCustomerDao->setFirstName($firstname);
		        $objCustomerDao->setLastName($lastname);
		        $objCustomerDao->setEmail($guestEmail);
		        $objCustomerDao->setTelephone($phoneNumber);
		        $objCustomerDao->setFax('');
		        $objCustomerDao->setNewsletter(0);
		        $objCustomerDao->setPaypalEC(1);
		        $objCustomerDao->setPaypalPayerid(0);
		        $objCustomerDao->setPassword($objPassword->encrypt($password));
		        $objCustomerDao->setCreatedTime('UTC_TIMESTAMP()');
		        $objCustomerDao->setModifiedTime('UTC_TIMESTAMP()');
		        $objCustomerDao->setCountryid($countryId);
		        $objCustomerDao->setNewsletter('unsubscribed');
		        $objCustomerDao->setAutoRegister(1);
		        
		        // insert the data
		    	$customerid = $common->insertUpdate(DB_TAG_SYSTEM, 'customers', $objCustomerDao->getArray());
				
				$objCustomerDao->setID($customerid);
				
		    	$objAddressBookDao->setCustomerid($customerid);
		    	
		       // insert the data
		        $addressid = $common->insertUpdate(DB_TAG_SYSTEM, 'address_book', $objAddressBookDao->getArray());
				
				$objAddressBookDao->setID($addressid);
				$objCustomerDao->setAddressid($addressid);
				
		        $sql = "UPDATE customers SET modifiedTime = UTC_TIMESTAMP(), default_address_id = '$addressid' WHERE id = $customerid";
				$common->update(DB_TAG_SYSTEM, $sql);
				
				// login
				
				$arrdata = array();
				$arrdata['uname'] = $lastname;		//--> add login name to session
			
				if($customerid > 0 && is_array($objSession->start($customerid, $arrdata))){
				}
				
				$_SESSION['customerInfo'] = serialize($objCustomerDao);
			}
		}
		
		$_SESSION['ordersInfo'] = serialize($objOrdersInfo);
	}
}

if(isset($_POST['address_edit'])){
	$objOrdersInfo->setDeliveryAddress(null);
		
	$_SESSION['ordersInfo'] = serialize($objOrdersInfo);
}


if(isset($_SESSION['customerInfo'])){
	$objCustomer 		= unserialize($_SESSION['customerInfo']);
	
	$customerid 		= $objCustomer->getID();
	$addressid			= $objCustomer->getAddressid();
}else if(!empty($customerid) && $customerid > 0){
	$customer = $common->getRow(DB_TAG_SYSTEM, "SELECT * FROM customers WHERE id =$customerid");
  		
	$objCustomerDao->setID($customerid);
	$objCustomerDao->setFirstName($customer['firstname']);
    $objCustomerDao->setLastName($customer['lastname']);
    $objCustomerDao->setEmail($customer['email']);
    $objCustomerDao->setTelephone($customer['telephone']);
    $objCustomerDao->setFax($customer['fax']);
    $objCustomerDao->setNewsletter($customer['newsletter']);
    $objCustomerDao->setPaypalEC($customer['paypal_ec']);
    $objCustomerDao->setPaypalPayerid($customer['paypal_payerid']);
    $objCustomerDao->setPassword($customer['password']);
    $objCustomerDao->setCreatedTime('UTC_TIMESTAMP()');
    $objCustomerDao->setModifiedTime('UTC_TIMESTAMP()');
    $objCustomerDao->setCountryid($customer['countryid']);
    $objCustomerDao->setAddressid($customer['default_address_id']);
    
    if(!empty($customer['default_address_id'])){
	    $arrAddress 	= $common->getRow(DB_TAG_PUBLIC, "SELECT a.id, a.customerid, a.gender, a.company, a.firstname, a.lastname, a.street, a.suburb, a.postcode, a.city, a.state, a.countryid, a.zoneid, c.name countryname FROM address_book a, countries c WHERE a.countryid = c.id AND a.id = " . $customer['default_address_id']);
		
		$objAddressBookDao	= new AddressBookDao();
		$objAddressBookDao->setArray($arrAddress);
		
		$objOrdersInfo->setCustomerAddress($objAddressBookDao);
		$objOrdersInfo->setDeliveryAddress($objAddressBookDao);
    }
    
    $_SESSION['customerInfo'] = serialize($objCustomerDao);
}


$oDeliveryAddress = $objOrdersInfo->getDeliveryAddress();
if(is_object($oDeliveryAddress)){
	$zoneid		= $objOrdersInfo->getDeliveryAddress()->getZoneid();
	$countryid	= $objOrdersInfo->getDeliveryAddress()->getCountryid();

}



$taxTotal 		= 0;
$shippingTotal 	= 0;
$saveDollar 	= 0;

$shippingFeeLimit	= 10000; // x 100. if product total amount more than this, than free shipping, only 48 zones for USA


$shippingZoneId	= 0;

/*------------- shipping start ------------------*/
if($countryid == 223 && $zoneid != 2 && $zoneid != 21 && $zoneid != 52){
	$shippingMethodID 	= 1;
	$shippingZoneId		= 12;// for 48 zone of USA
	
}else if($countryid == 223){// for PR, AK, HI
	$sql = "SELECT id FROM shipping_method WHERE id IN (SELECT shippingMethodID FROM shipping_fee WHERE zoneID = $shippingZoneId AND status='yes')";
	$shippingMethodID = $common->getColumn(DB_TAG_PUBLIC, $sql);
	
	if(empty($shippingMethodID)){// default shipping method
		$shippingMethodID 	= 3;
	}
}else{
	$shippingMethodID 	= 4;
}

$sql = "SELECT id, name FROM shipping_method WHERE id = $shippingMethodID";
$arrShippingMethod = $common->getHash(DB_TAG_PUBLIC, $sql);


$arrShippingTypeID 	= array();

$arrProductList = $objCart->getProductList();
foreach($arrProductList as $product){
	$shippingTypeID = $product->getShippingTypeID();
	
	$sql = "SELECT amount, amount2 FROM shipping_fee WHERE zoneID = $shippingZoneId AND shippingMethodID = $shippingMethodID AND shippingTypeID = $shippingTypeID";
	
	$arrShippingFee = $common->getRow(DB_TAG_PUBLIC, $sql);
	
	if(count($arrShippingFee) > 0){
		if( array_key_exists($shippingTypeID, $arrShippingTypeID)){
			$shippingTotal += $arrShippingFee['amount2'];
		}else{
			$shippingTotal += $arrShippingFee['amount'];
		}
		
		if($product->getQuantity() > 1){
			$shippingTotal += ($product->getQuantity() - 1) * $arrShippingFee['amount2'];
		}
		
		$arrShippingTypeID[$shippingTypeID] = $shippingTypeID;
	}else{// default value
		if($countryid == 223){
			if( array_key_exists($shippingTypeID, $arrShippingTypeID)){
				$shippingTotal += 600;
			}else{
				$shippingTotal += 995;
			}
			
			$arrShippingTypeID[$shippingTypeID] = $shippingTypeID;
		}else if($countryid == 38){//Canada
			if( array_key_exists($shippingTypeID, $arrShippingTypeID)){
				$shippingTotal += 1400;
			}else{
				$shippingTotal += 3495;
			}
			
			$arrShippingTypeID[$shippingTypeID] = $shippingTypeID;
		}else{//other countries
			if( array_key_exists($shippingTypeID, $arrShippingTypeID)){
				$shippingTotal += 5000;
			}else{
				$shippingTotal += 6500;
			}
			
			$arrShippingTypeID[$shippingTypeID] = $shippingTypeID;
		}
	}
}


if($productTotal > $shippingFeeLimit && $countryid == 223 && $shippingZoneId != 2 && $shippingZoneId != 21 && $shippingZoneId != 52){
	$shippingTotal = 0;
}

/*------------- shipping end ------------------*/

/*------------- tax start ------------------*/
$arrTaxReal 	= array();

if($zoneid > 0){
	$arrTax = $common->getHash(DB_TAG_PUBLIC, "SELECT tr.id, tr.rate FROM tax_class tc, tax_rates tr WHERE tc.id = tr.classID AND tr.zoneID = $zoneid ORDER BY priority");
	foreach($arrTax as $key => $value){
		$taxSubTotal = $value * $productTotal;
		
		$taxTotal += $taxSubTotal;
	}
}

/*------------- tax end ------------------*/

if(empty($countryId))
	$countryId	= 223;

$arrCountries = $objCountry->getGroupList();

$arrZones = $objZone->getGroupList($countryId);
if(count($arrZones) > 0)
	$hasZone = 'yes';


$taxTotal 		= round($taxTotal / 1000000 , 2);
$saveDollar 	= round($objCart->getSaveOff() / 100, 2);
$shippingTotal	= round($shippingTotal / 100, 2);
$productTotal	= round($productTotal / 100, 2);

$allTotal 		= $productTotal + $taxTotal + $shippingTotal;


$objOrdersAccount	= new OrdersAccount();
$objOrdersAccount->setTaxTotal($taxTotal);
$objOrdersAccount->setShippingTotal($shippingTotal);
$objOrdersAccount->setAllTotal($allTotal);
$objOrdersAccount->setSaveOff($saveDollar);
$objOrdersAccount->setProductTotal($productTotal);


$objOrdersInfo->setAccount($objOrdersAccount);
$objOrdersInfo->setShippingTypeID($shippingMethodID);


$_SESSION['ordersInfo'] = serialize($objOrdersInfo);
$_SESSION['cart'] 		= serialize($objCart);



/*----- out html -----*/
$smarty = new Smarty();	//-- out template
$smarty->template_dir 	= TEMPLATE_DIR;
$smarty->compile_dir  	= COMPILE_DIR;
$smarty->cache_dir  	= CACHE_DIR;

$smarty->force_compile 	= true;
$smarty->debugging 		= false;
$smarty->caching 		= false;
$smarty->cache_lifetime = 120;

$smarty->assign('HOME_URL', '.');
$smarty->assign('HOME_URL_HTTP', HOME_URL);

$smarty->assign('error_message', $error_message);

$smarty->assign('firstname', $firstname);
$smarty->assign('lastname', $lastname);
$smarty->assign('zipcode', $zipcode);
$smarty->assign('city', $city);
$smarty->assign('street', $street);
$smarty->assign('state', $state);
$smarty->assign('phoneNumber', $phoneNumber);


$smarty->assign('paymentMethod', $paymentMethod);

$smarty->assign('arrZones', $arrZones);
$smarty->assign('zoneid', $zoneid);
$smarty->assign('hasZone', $hasZone);

$smarty->assign('countryId', $countryId);
$smarty->assign('arrCountries', $arrCountries);

$smarty->assign('arrShippingMethod', $arrShippingMethod);
$smarty->assign('shippingMethodId', $shippingMethodID);

$smarty->assign('shippingTotal', $shippingTotal);
$smarty->assign('taxTotal', $taxTotal);
$smarty->assign('saveDollar', $saveDollar);
$smarty->assign('productTotal', $productTotal);
$smarty->assign('allTotal', $allTotal);

$smarty->assign('objStrings', $objStrings);
$smarty->assign('objCart', $objCart);
$smarty->assign('objOrdersInfo', $objOrdersInfo);
$smarty->assign('oDeliveryAddress', $oDeliveryAddress);
$smarty->assign('objCustomerDao', $objCustomerDao);

$smarty->assign('isLogin', $isLogin);

$smarty->display('checkout.html');
?>
